<template>
  <div style="height: 100%">
    <div class="searchBox">
      <form-box :fields="searchField" :is-filter="true" :submit-handle="searchHandle" />
    </div>
    <div class="baby-box">
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <el-button type="primary" :disabled="classes.length <= 0" @click="add">新增</el-button>
        <div v-loading="loading" class="info">
          <div class="info_item">
            <div>班级总数</div>
            <span>{{ info.headcount }}</span>
          </div>
          <div class="info_item">
            <div>已接种人数：</div>
            <span>{{ info.vaccinated }}</span>
          </div>
          <div class="info_item">
            <div>未接种人数：</div>
            <span>{{ info.unvaccinated }}</span>
          </div>
        </div>
      </div>
      <Ltable
        v-if="list.length > 0 || loading"
        :data="list"
        :loading="loading"
        :columns="config.vaccineColumns"
        class="mt16"
      >
        <template #type="{ row }">
          {{ getType(row.type) }}
        </template>
        <template #clssesName="{ row }">
          {{ getClassName(row.classesId) }}
        </template>
        <template #state="{ row }">
          <el-tag :type="row.state == 0 ? 'danger' : 'success'">
            {{ row.state == 0 ? '未接种' : '已接种' }}
          </el-tag>
        </template>
        <template #inoculateTime="{ row }">
          {{ row.state == 0 ? '-' : date.formatTimestamp(new Date(row['inoculateTime']).getTime(), 'date') }}
        </template>
        <template #operate="{ row }">
          <el-button size="mini" type="text" class="yellow" @click="getDetails(row)">详情</el-button>
          <el-button size="mini" type="text" class="blue" @click="edit(row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除当前疫苗记录?"
            class="ml10"
            @confirm="() => delChildrenVaccines(row.id)"
            @onConfirm="() => delChildrenVaccines(row.id)"
          >
            <el-button slot="reference" size="mini" type="text" class="red">删除</el-button>
          </el-popconfirm>
        </template>
      </Ltable>
      <div v-else class="quesheng">
        <img src="@/assets/quesheng.png" alt="">
        <span>暂无数据</span>
      </div>
      <div v-if="list.length > 0 && !loading" style="text-align: right;">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      size="680px"
      :wrapper-closable="false"
    >
      <div style="padding: 0 30px">
        <from-page
          ref="fromRef"
          class="mt10"
          :label-width="null"
          :rules="config.vaccineRules"
          :from-config="vaccine"
          :value="value"
          @selectChange="selectChange"
          @submitForm="submitForm"
        />
      </div>
    </el-drawer>
    <el-drawer
      title="详情"
      :visible.sync="show"
      :destroy-on-close="true"
      custom-class="add-drawer"
      size="680px"
      :wrapper-closable="false"
    >
      <div style="padding: 0 24px">
        <from-page
          ref="fromRef"
          class="mt10"
          :label-width="null"
          :from-config="vaccineFrom"
          :value="detail"
          :but-show="false"
          :disabled-from="true"
        />
        <div class="title mt20">接种历史</div>
        <el-timeline>
          <div class="timeline">
            <el-timeline-item v-for="(item, index) in detail.inoculates" :key="index">
              <div class="date">
                <span>{{ item.inoculateTime }}</span>
                <span>{{ getType(item.type) }}</span>
              </div>
              <div style="margin-top: 10px;color: #77778C">{{ item.remark }}</div>
            </el-timeline-item>
          </div>
        </el-timeline>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as config from '../config'
import FromPage from '@/components/Basic/FromPage/index'
import { mapGetters } from 'vuex'
import { getClassesByArea } from '@/api/common'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import { selChildrenVaccinesPage, delChildrenVaccines, selChildrenVaccinesDetails, selClassDataStatistics } from '../api'
import axios from 'axios'
import * as date from '@/utils/date'
export default {
  name: 'Vaccine',
  components: {
    FromPage
  },
  data () {
    return {
      info: {},
      detail: {},
      vaccineFrom: [{
        type: 'select',
        label: '所在班级',
        value: 'classesId',
        placeholder: '请选择所在班级'
      },
      {
        type: 'select',
        label: '宝宝姓名',
        value: 'name',
        placeholder: '请输入宝宝姓名'
      }],
      show: false,
      title: '新增疫苗记录',
      date,
      value: {},
      contacts: [],
      config,
      action: `${process.env.VUE_APP_BASE_API}`,
      headers: { Authorization: getToken() },
      drawer: false,
      total: 1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: '',
        state: ''
      },
      loading: true,
      list: [],
      classId: '',
      classes: [],
      log: null,
      babyList: []
    }
  },
  computed: {
    ...mapGetters(['curArea', 'user']),
    searchField () {
      const { classId } = this
      return [
        {
          key: 'classId',
          label: '班级名称',
          type: 'select',
          initialValue: classId,
          fieldProps: {
            options: this.classes,
            props: { value: 'id', label: 'name' }
          },
          events: {
            change: val => this.classChange(val)
          }
        },
        {
          key: 'type',
          label: '疫苗',
          type: 'select',
          initialValue: this.queryParams.type,
          fieldProps: {
            options: config.fromVaccine,
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'state',
          label: '接种状态',
          type: 'select',
          initialValue: this.queryParams.state,
          fieldProps: {
            options: [{ value: 0, label: '未接种' }, { value: 1, label: '接种' }],
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'name',
          label: '宝宝姓名'
        }
      ]
    },
    vaccine () {
      config.vaccineFrom[1]['option'] = this.babyList
      return config.vaccineFrom
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    getDetails (item) {
      config.vaccineFrom[4]['show'] = true
      config.vaccineFrom[4]['show'] = true
      config.vaccineFrom[4]['show'] = true
      this.loading2()
      selChildrenVaccinesDetails({ id: item.childrenId }).then(res => {
        this.detail = { name: item.name, classesId: this.getClassName(item.classesId) }
        this.detail['inoculates'] = res
        this.show = true
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    async edit (row) {
      config.vaccineFrom[0]['disabled'] = true
      config.vaccineFrom[3]['disabled'] = true
      config.vaccineFrom[4]['show'] = false
      this.loading2()
      // const req = await selChildrenVaccinesDetails({ id: row['childrenId'] })
      // const types = []
      // for (let i = 0; i < req.length; i++) {
      //   types.push(req[i]['type'] + '')
      // }
      // config.vaccineFrom[2]['option'] = config.vaccineFrom[2]['option'].filter(item => !types.includes(item.value + ''))
      await this.getbabyList(row.classesId, row.childrenId)
      this.title = '编辑疫苗信息'
      this.value = JSON.parse(JSON.stringify(row))
      if (this.value['state'] === 1) {
        this.value['inoculateTime'] = this.date.formatTimestamp(new Date(row['inoculateTime']).getTime())
      } else {
        this.value['inoculateTime'] = ''
      }
      this.value['type'] = this.value['type'] + ''
      this.drawer = true
      this.log && this.log.close()
    },
    delChildrenVaccines (id) {
      this.loading2()
      delChildrenVaccines({ id }).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.init()
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    getType (type) {
      return config.fromVaccine.find(item => item.value === type + '')['label']
    },
    init () {
      this.queryParams.pageNum = 1
      this.list = []
      this.getList()
    },
    add () {
      this.title = '新增疫苗记录'
      config.vaccineFrom[0]['disabled'] = false
      config.vaccineFrom[3]['disabled'] = false
      config.vaccineFrom[4]['show'] = true
      this.value = {}
      this.drawer = true
    },
    selectChange (e) {
      const { type, value } = e
      if (type === 'classesId') {
        config.vaccineFrom[3]['loading'] = true
        this.getbabyList(value)
      }
    },
    getClassName (id) {
      let name = ''
      for (let i = 0; i < this.classes.length; i++) {
        if (this.classes[i]['id'] === id) {
          name = this.classes[i]['name']
        }
      }
      return name
    },
    // 获取宝宝列表
    getbabyList (classId, id) {
      request({
        url: 'web/checkrecord/check_record_by_classId',
        method: 'post',
        params: { classId }
      }).then(res => {
        this.babyList = (res[0] ? (res[0].childrenList || []) : [])
        config.vaccineFrom[3]['option'] = (res[0] ? (res[0].childrenList || []) : [])
        config.vaccineFrom[3]['option'] = config.vaccineFrom[3]['option'].map(item => {
          if (item['childrenId'] === id) {
            item['select'] = true
          }
          return item
        })
        config.vaccineFrom[3]['loading'] = false
      })
    },
    beforeClose () {
      this.$refs.fromRef.resetFields()
      this.drawer = false
    },
    async submitForm (e) {
      const { user } = this
      this.loading2()
      if (this.value['id']) {
        axios.post('/api/web/children/editChildrenVaccines', { ...e, type: e['type'], inoculateTime: e['inoculateTime'], remark: e['remark'], state: 1, createUserId: user.id, createUserName: user.realName }, {
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => {
          if (res.data.code === '000000') {
            this.beforeClose()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.init()
            return
          }
          this.$message.error(res.data.msg)
        }).finally(() => {
          this.log && this.log.close()
        })
        return
      }
      let babys = []
      if (e['name'] && e['name'].length > 0) {
        let baby1 = e['name'].filter(item => item['select'])
        let baby2 = e['name'].filter(item => !item['select'])
        baby1 = baby1.map((item) => {
          return { name: item['childrenName'], type: e['type'], classesId: e['classesId'], state: 1, inoculateTime: e['inoculateTime'], childrenId: item['childrenId'], createUserId: user.id, createUserName: user.realName }
        })
        baby2 = baby2.map((item) => {
          return { name: item['childrenName'], type: e['type'], classesId: e['classesId'], state: 0, inoculateTime: e['inoculateTime'], childrenId: item['childrenId'], createUserId: user.id, createUserName: user.realName }
        })
        babys = [...baby1, ...baby2]
      } else if (this.babyList.length > 0) {
        babys = this.babyList.map((item) => {
          return { name: item['childrenName'], type: e['type'], classesId: e['classesId'], state: 0, inoculateTime: e['inoculateTime'], childrenId: item['childrenId'], createUserId: user.id, createUserName: user.realName }
        })
      } else {
        this.$message.error('添加失败：暂无宝宝信息')
      }
      axios.post('/api/web/children/addChildrenVaccines', babys, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data.code === '000000') {
          this.beforeClose()
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.init()
          return
        }
        this.$message.error(res.data.msg)
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    // 加载动画
    loading2 (text = '请稍后...') {
      this.log = this.$loading({
        lock: true,
        text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /** 编辑按钮操作 */
    handleEdit () {
      this.title = '编辑宝宝'
      this.drawer = true
    },
    searchHandle (res) {
      this.queryParams.pageNum = 1
      this.list = []
      this.queryParams = { ...this.queryParams, ...res }
      this.getList()
    },
    getList () {
      const queryParams = JSON.parse(JSON.stringify(this.queryParams))
      queryParams.pageNum--
      queryParams['classesId'] = queryParams['classId']
      selClassDataStatistics(queryParams).then(res => {
        this.info = res
      })
      this.loading = true
      selChildrenVaccinesPage(queryParams).then(res => {
        this.loading = false
        this.list = res.content
        this.total = res.totalElements
      })
    },
    // 获取班级列表
    getClassList () {
      const { curArea, queryParams } = this
      getClassesByArea({ areaId: curArea.areaId, category: 1 }).then(res => {
        this.classes = res || []
        const id = this.classes[0] ? this.classes[0].id : ''
        this.classChange(id)
        config.vaccineFrom[0]['option'] = this.classes
        queryParams['classId'] = id
        this.getbabyList(id)
        this.getList()
      })
    },
    // 选择班级
    classChange (val) {
      this.classId = val
    }
  }
}
</script>

<style lang="scss" scope>
.drawer-box {
  padding: 16px;
  background: #FAFAFD;
  border-radius: 4px;
  border: 1px solid #EBEBEE;
}

.drawer-top {
  display: flex;
  justify-content: space-between;
  align-items: center;

  div {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    text-align: left;
    font-style: normal;
    text-transform: none;
    font-size: 18px;
  }
}

.baby-box .pagination-container {
  margin-top: 0px;
}

.baby-table {
  width: 100%;
  height: calc(100% - 80px);
}

.baby-box {
  margin-top: 16px;
  background-color: #FFFFFF;
  border-radius: 8px;
  padding: 24px;
}

.baby-box {
  th.is-leaf {
    height: 66px;
  }

  th {
    color: #000;
    font-size: 17px;
    background: #FAFAFA;
    font-family: PingFang SC;
    font-weight: bold;
  }

  td {
    padding: 20px 0
  }
}

.quesheng {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;

  span {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    font-style: normal;
    text-transform: none;
    margin-top: 32px;
  }
}

.searchBox .el-form-item {
  margin-bottom: 0 !important;
}

.baby-box .el-table--border {
  border: 0;
}

.searchBox {
  background: #FFFFFF;
  border-radius: 8px;
  padding: 16px 20px;
}

.hint {
  margin-top: 10px;
}

.weekend-bg {
  background: #7d7d7f;
  width: 100%;
  height: 100%;
}

.el-table {
  .cell {
    padding: 0;
  }
}

.el-table {
  th {
    .cell {
      padding: 0;
    }
  }

}

.timeline li:nth-child(4n+1) {
  .el-timeline-item__node {
    border: 3px solid #0052D9 !important;
    background-color: transparent !important;
  }
}

.timeline li:nth-child(4n+2) {
  .el-timeline-item__node {
    border: 3px solid #2BA471 !important;
    background-color: transparent !important;
  }
}

.timeline li:nth-child(4n+3) {
  .el-timeline-item__node {
    border: 3px solid #D54941 !important;
    background-color: transparent !important;
  }
}

.timeline li:nth-child(4n+4) {
  .el-timeline-item__node {
    border: 3px solid #E37318 !important;
    background-color: transparent !important;
  }
}

.timeline .el-timeline-item__wrapper {
  top: 0 !important;
}

.date {
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #000000;
  text-align: left;
  font-style: normal;
  text-transform: none;

  span:nth-child(1) {
    font-size: 14px;
    color: #77778C;
    margin-right: 32px;
  }
}

.title {
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  text-align: left;
  font-style: normal;
  text-transform: none;
  padding-bottom: 25px;
}

.info {
  background: #FAFAFD;
  border-radius: 4px;
  border: 1px solid #EBEBEE;
  padding: 6px 16px;
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: 400;
  font-size: 14px;
  color: #333333;
  text-align: left;
  font-style: normal;
  text-transform: none;
  display: flex;
  align-items: center;

  &_item {
    display: flex;
    align-items: center;

    div {
      margin-right: 16px;
    }

    span {
      font-family: Source Han Sans SC, Source Han Sans SC;
      font-weight: bold;
      font-size: 14px;
      color: #006BE7;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
  }

  &_item:nth-child(1) {
    span {
      margin-right: 16px;
    }
  }

  &_item:nth-child(2) {
    span {
      color: #7FC73C;
      margin-right: 16px;
    }
  }

  &_item:nth-child(3) {
    span {
      color: #FF5757;
    }
  }

}
</style>
